import axios from "axios";
import { Message } from "element-ui";
import store from "@/store";
const service = axios.create({
  baseURL: "http://localhost:8080",
  timeout: 50000,
});

// request interceptor
service.interceptors.request.use(
  (config) => {
    let index = config.url.indexOf("login");
    if (index != -1) {
      store.state.token = "";
      window.sessionStorage.removeItem("token");
    }
    //这里需要携带请求头进行认证
    const token = store.getters.token || window.sessionStorage.getItem("token");
    if (token) {
      config.headers.Authorization = token;
    }
    return config;
  },
  (error) => {
    console.log(error);
    return Promise.reject(error);
  }
);

// response interceptor
service.interceptors.response.use(
  (response) => {
    const res = response.data;

    if (res.code !== 200) {
      Message({
        message: res.message || "未知的异常",
        type: "error",
        duration: 5 * 1000,
      });

      return Promise.reject(new Error(res.message || "未知的异常"));
    } else {
      return res;
    }
  },
  (error) => {
    console.log("err" + error);
    Message({
      message: error.message,
      type: "error",
      duration: 5 * 1000,
    });
    return Promise.reject(error);
  }
);

export default service;
